import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import Login from "../components/Login/index.vue";
import Error404 from "../components/Error404/index.vue";
import Loading from "../components/Loading/index.vue";
import { useRouteBread } from "@/store/routebread.store.js";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { ElLoading } from "element-plus";
import { createNavGuard } from "./routerBeforeEach"; // 面包屑
import data from "@/utils/route";
import routeConfig from "@/utils/route.config";

// 常驻路由
const routes = [
  {
    path: "/",
    name: "login",
    component: Login,
  },
  {
    path: "/threeColumnLayout",
    name: "threeColumnLayout",
    redirect: routeConfig.storeDefaultPath,
    component: () => import("../components/ThreeColumnLayout/index.vue"),
    children: [
      {
        path: routeConfig.storeDefaultPath,
        name: routeConfig.storeDefaultName,
        icon: "House",
        id: 999,
        component: () => import("@/views/HomePage/index.vue"),
      },
    ],
  },
  {
    path: "/:path(.*)*",
    name: "404",
    component: Error404,
  },
];

let router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由递归变成路由规则
const routerRecursion = (data, router) => {
  data.forEach((item) => {
    if (item.children && item.children.length !== 0) {
      routerRecursion(item.children, router);
    } else {
      router.addRoute("threeColumnLayout", {
        path: item[routeConfig.path],
        name: item[routeConfig.name],
        icon: item[routeConfig.icon],
        id: item[routeConfig.id],
        // component: () => import(`@/views/${item.component}/index.vue`),
        component: () =>
          import(`@/views/${item[routeConfig.component]}/index.vue`),
      });
    }
  });
};

// 如果本地有路由了，不用调接口了
if (localStorage.getItem("routerList")) {
  routerRecursion(
    JSON.parse(localStorage.getItem("routerList")).routerList,
    router
  );
}

router.beforeEach(async (to, from, next) => {
  // console.log(to, from, router.options.routes);
  if (!localStorage.getItem("token") && to.path !== "/") {
    ElMessage.warning("token已过期或者不存在, 请重新登录 !");
    next({ path: "/" });
  } else if (to.path === "/") {
    next();
  } else if (
    to.path !== "/" &&
    from.path === "/" &&
    !localStorage.getItem("routerList")
  ) {
    let loadingInstance = ElLoading.service({
      text: "菜单加载中, 请稍等!",
      background: "rgba(0, 0, 0, 0.8)",
    });
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve(data);
        loadingInstance.close();
      }, 2000);
    }).then((res) => {
      const store = useRouteBread();
      let { routerList } = storeToRefs(store);
      routerList.value = res;
      routerRecursion(res, router);
      next();
    });
  } else {
    // 开启进度条
    NProgress.start();
    next();
  }
  createNavGuard(router);
});

router.afterEach(() => {
  // 关闭进度条
  NProgress.done();
});

export default router;
